<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="profile-header">
          <h2>个人信息</h2>
          <el-button type="primary" @click="editMode = !editMode">
            {{ editMode ? '取消编辑' : '编辑信息' }}
          </el-button>
        </div>
      </template>
      
      <el-form 
        :model="profileForm" 
        :rules="profileRules" 
        ref="profileFormRef" 
        label-width="100px"
        :disabled="!editMode"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username"></el-input>
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="profileForm.realName"></el-input>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-input v-model="roleDisplay" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="注册时间">
          <el-input v-model="profileForm.createdAt" disabled></el-input>
        </el-form-item>
        
        <el-form-item v-if="editMode">
          <el-button type="primary" @click="saveProfile" :loading="loading">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="profile-card" style="margin-top: 20px;">
      <template #header>
        <div class="profile-header">
          <h2>账号安全</h2>
        </div>
      </template>
      
      <div class="security-items">
        <div class="security-item">
          <div class="security-info">
            <h4>账号密码</h4>
            <p>定期修改密码可以提高账号安全性</p>
          </div>
          <el-button type="primary" plain @click="showPasswordDialog">修改密码</el-button>
        </div>
        
        <el-divider></el-divider>
        
        <div class="security-item">
          <div class="security-info">
            <h4>登录状态</h4>
            <p>上次登录时间: {{ lastLoginTime }}</p>
          </div>
          <el-button type="danger" plain @click="handleLogout">退出登录</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 修改密码弹窗 -->
    <el-dialog
      title="修改密码"
      v-model="passwordDialogVisible"
      width="400px"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword" :loading="passwordLoading">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../stores/user'
import axios from 'axios'

const router = useRouter()
const userStore = useUserStore()
const profileFormRef = ref(null)
const passwordFormRef = ref(null)
const editMode = ref(false)
const loading = ref(false)
const passwordLoading = ref(false)
const lastLoginTime = ref('--')
const passwordDialogVisible = ref(false)

// 表单数据
const profileForm = reactive({
  id: userStore.user.id,
  username: userStore.user.username,
  realName: userStore.user.realName,
  role: userStore.user.role,
  createdAt: userStore.user.createdAt
})

// 密码表单数据
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 角色显示
const roleMap = {
  'admin': '管理员',
  'teacher': '教师',
  'reviewer': '审核员'
}

const roleDisplay = computed(() => {
  return roleMap[profileForm.role] || '未知'
})

// 表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ]
}

// 密码验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度至少为6个字符'))
  } else {
    if (passwordForm.confirmPassword !== '') {
      passwordFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = {
  newPassword: [
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ]
}

// 保存个人信息
const saveProfile = () => {
  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await axios.post('http://localhost:8081/api/user/update', {
          id: profileForm.id,
          username: profileForm.username,
          realName: profileForm.realName,
          role: profileForm.role,
          createdAt: profileForm.createdAt
        }, {
          headers: {
            'Authorization': userStore.token
          }
        })
        
        if (response.data.code === 200) {
          // 更新本地存储的用户信息
          const updatedUser = {
            ...userStore.user,
            username: profileForm.username,
            realName: profileForm.realName
          }
          userStore.setUser(updatedUser)
          
          ElMessage.success('个人信息更新成功')
          editMode.value = false
        } else {
          ElMessage.error(response.data.msg || '更新失败')
        }
      } catch (error) {
        if (error.response && error.response.data) {
          ElMessage.error(error.response.data.msg || '更新失败')
        } else {
          ElMessage.error('更新失败，请检查网络连接')
        }
        console.error('更新错误:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 显示修改密码弹窗
const showPasswordDialog = () => {
  passwordDialogVisible.value = true
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 修改密码
const changePassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        // 使用URLSearchParams格式发送表单数据
        const params = new URLSearchParams()
        params.append('id', profileForm.id)
        params.append('password', passwordForm.newPassword)
        
        const response = await axios.post('http://localhost:8081/api/user/change-password', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': userStore.token
          }
        })
        
        if (response.data.code === 200) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
        } else {
          ElMessage.error(response.data.msg || '密码修改失败')
        }
      } catch (error) {
        if (error.response && error.response.data) {
          ElMessage.error(error.response.data.msg || '密码修改失败')
        } else {
          ElMessage.error('密码修改失败，请检查网络连接')
        }
        console.error('密码修改错误:', error)
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  profileForm.username = userStore.user.username
  profileForm.realName = userStore.user.realName
  profileFormRef.value.resetFields()
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout()
    router.push('/login')
    ElMessage.success('已退出登录')
  }).catch(() => {})
}

// 获取上次登录时间
onMounted(() => {
  // 这里可以从后端获取上次登录时间，暂时使用当前时间
  lastLoginTime.value = new Date().toLocaleString('zh-CN')
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-items {
  padding: 0 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.security-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.security-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}
</style>